﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace JTT.Dev.Toolkit
{
    /// <summary>
    /// 加密解密与编码模块
    /// </summary>
    namespace Crypto
    {
        /// <summary>
        /// 加密解密辅助类
        /// </summary>
        public static class CryptoHelper
        {
            /// <summary>
            /// URL编码
            /// </summary>
            /// <param name="_SourceString"></param>
            /// <returns></returns>
            public static String URLEncoding(this String _SourceString)
            {
                return System.Web.HttpUtility.UrlEncode(_SourceString, System.Text.Encoding.UTF8);
            }


            /// <summary>
            /// Javascript中JSEscape编码的服务端实现
            /// </summary>
            /// <param name="instr"></param>
            /// <returns></returns>
            public static string ToJSEscapeString(this String _SourceString)
            {
                return Microsoft.JScript.GlobalObject.escape(_SourceString);
            }

            /// <summary>
            /// 获得Unicode字符串
            /// </summary>
            /// <param name="_SourceString"></param>
            /// <returns></returns>
            public static String ToUnicodeString(this String _SourceString)
            {
                String OutString = "";
                if (!string.IsNullOrEmpty(_SourceString))
                {
                    for (int i = 0; i < _SourceString.Length; i++)
                    {
                        OutString += @"\u" + ((int)_SourceString[i]).ToString("x").ToUpper();
                    }
                }
                return OutString;
            }

            /// <summary>
            /// MD5加密
            /// </summary>
            /// <param name="_SourceString"></param>
            /// <returns></returns>
            public static String ToMD5String(this String _SourceString)
            {
                MD5 MyMD5 = MD5.Create();
                byte[] MD5Data = MyMD5.ComputeHash(Encoding.UTF8.GetBytes(_SourceString));
                StringBuilder MyStringBuilder = new StringBuilder();
                for (int i = 0; i < MD5Data.Length; i++)
                {
                    MyStringBuilder.Append(MD5Data[i].ToString("x2"));
                }
                return MyStringBuilder.ToString().ToUpper();
            }
        }
    }
}
